package com.example.spring_mysql.controller;

import org.springframework.http.MediaType
import org.springframework.messaging.handler.annotation.MessageMapping
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter
import reactor.core.publisher.Flux
import java.time.Duration

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hjw
 * @since 2025-06-11
 */
@Controller
class UserController {

    @GetMapping("/th")
    fun hello(model: Model): String {
        model.addAttribute("name", "张三")
        return "th1"
    }

    @GetMapping("/stream", produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
    fun stream(): SseEmitter {
        val emitter = SseEmitter()
        Thread {
            try {
                for (i in 1..10) {
                    emitter.send(SseEmitter.event().data("data-$i"))
                    Thread.sleep(1000)
                }
                emitter.complete()
            } catch (e: Exception) {
                emitter.completeWithError(e)
            }
        }.start()
        return emitter
    }

    @MessageMapping("stream")
    fun stream(data: String): Flux<String> =
        Flux.interval(Duration.ofSeconds(1))
            .map { "Stream: $data - $it" }

    @MessageMapping("channel")
    fun channel(input: Flux<String>): Flux<String> =
        input.map { "Echo: $it" }

    @MessageMapping("chat")
    fun chat(messagesFromClient: Flux<String>): Flux<String> {
        return messagesFromClient
            .doOnNext { println("服务端收到: $it") }
            .map { clientMsg -> "服务端响应: [$clientMsg]" }
    }
}

